import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_rfid_dmo/rfid/utils/data_convert.dart';
import 'epc_manger.dart';
import 'package:flutter_rfid_dmo/rfid/model/device_info.dart';
import 'package:flutter_rfid_dmo/rfid/ble/ble_manger.dart';
import 'model/epc_data.dart';
import 'model/rfid_model.dart';

class RFIDConnection {
  static final RFIDConnection _instance = RFIDConnection._internal();
  factory RFIDConnection() => _instance;
  RFIDConnection._internal();

  // 蓝牙管理器
  final RfidBleManager bleManager = RfidBleManager();

  // 帧序号
  int _frameSeq = 0;
  // 功能字节
  int _funcByte0 = -80;
  int _funcByte1 = 0x01;
  List<int> _uhfRFset = [];

  // 其它属性
  final EpcManager _epcManager = EpcManager();
  final StreamController<RfidResult> _resultController =
      StreamController<RfidResult>.broadcast();
  Stream<RfidResult> get resultStream => _resultController.stream;

  // 初始化
  void initialize(Function(bool)? onStateChanged) {
    bleManager.initialize(_decode, onStateChanged);
  }

  void onDispose() {
    bleManager.onDispose();
  }

  // 断开连接
  Future<void> disconnect() async {
    await bleManager.disconnect();
    rxReset();
  }

  // 连接设备
  Future<bool> connectDevice(BluetoothDevice device) async {
    try {
      await bleManager.connectDevice(device);
      return true;
    } catch (e) {
      return false;
    }
  }

  // 发送命令
  Future<bool> sendRFIDCmd(List<int> data, {int len = 0}) async {
    if (!bleManager.isConnected || bleManager.rxCharacteristic == null) {
      return false;
    }

    try {
      // 构建命令帧
      List<int> frame = _buildCommandFrame(data, len);
      await bleManager.rxCharacteristic?.write(frame);
      return true;
    } catch (e) {
      return false;
    }
  }

  // 构建命令帧
  List<int> _buildCommandFrame(List<int> data, int len) {
    int i = 0;
    int checkSum = 0;
    List<int> btTextbuf = List.filled(20 + len, 0);

    // 初始化命令帧
    btTextbuf[i++] = -105; // -105
    btTextbuf[i++] = 0;
    btTextbuf[i++] = -128; // -128
    btTextbuf[i++] = 0;
    btTextbuf[i++] = 15;

    // 背夹MAC地址（A0-A5）	6字节，低字节在前
    List<int> macAdd =
        DataConvert.getStringHex(bleManager.device!.remoteId.str);
    btTextbuf.setRange(i, i + 6, macAdd);
    i += 6;

    // 第二组数据
    btTextbuf[i++] = -105; // -105
    btTextbuf[i++] = len & 0xFF;
    btTextbuf[i++] = (len >> 8) & 0xFF;

    // 帧序号（SEQ）	1字节，0-255循环计数（重发帧不递增）
    btTextbuf[i++] = _frameSeq;

    // 控制码（C）	定义传输方向、主从标志、错误状态）
    // D7（方向）: 0=手机→背夹，1=背夹→手机
    // D6（主从）: 0=从设备，1=主设备
    // D5（错误）: 0=正常，1=异常（数据域含错误码）
    // D4-D0: 保留（默认0）
    btTextbuf[i++] = 64;

    // 功能码（Fn）	2字节（F0+F1），低字节在前
    btTextbuf[i++] =
        _funcByte0; // 0x01: 查询通用参数（如设备状态;）0xB0: 背夹控制（如电源管理）; 0x20: 超高频RFID操作
    btTextbuf[i++] =
        _funcByte1; // 设备状态查询（F0=0x01, F1=0x02）; RFID盘存（F0=0x20, F1=0x05）, 支持EPC/TID读取，可设置盘存模式（按次数/时间）

    // 数据域（DATA）: 可变长度，内容由功能码决定
    int j;
    if (len > 0 && data.isNotEmpty) {
      for (j = 0; j < len; ++j) {
        btTextbuf[i++] = data[j];
      }
    }

    // 校验码（CS）	从起始符到校验码前所有字节的模256和
    for (j = 0; j < i; ++j) {
      checkSum += btTextbuf[j];
    }
    btTextbuf[i++] = checkSum; // 执行的次数

    // 结束符	0xE9（固定值）
    btTextbuf[i] = -23; // -23
    _frameSeq++;
    debugPrint(
        '发送命令成功: $_index bytes [${DataConvert.getHexString(btTextbuf, 0, btTextbuf.length)}]"');
    return btTextbuf;
  }

  // 添加头部检测和数据解析逻辑
  bool _headed = false;
  int _hindex = 0;
  int _index = 0;
  int _frameLen = 0;
  final List<int> _recBuf = List.filled(5100, 0);
  final List<int> _head = [0x97]; // -105 开头

  void rxReset() {
    _headed = false;
    _index = 0;
    _frameLen = 0;
    _hindex = 0;
  }

  void _decode(List<int> data, {bool isBacker = true}) {
    if (isBacker) {
      _decodeBacker(data);
    } else {
      _decodeRF(data);
    }
  }

  List<int> byteBuffer = [];
  _decodeRF(
    List<int> data,
  ) {
    byteBuffer.addAll(data);

    while (byteBuffer.length >= 8) {
      try {
        const startIndex = 0;
        final head = byteBuffer[startIndex];

        if (head != 0xA0) {
          byteBuffer.removeAt(0);
          continue;
        }

        if (byteBuffer.length < 2) break;
        final len = byteBuffer[1];
        final dataLength = len;

        if (byteBuffer.length < 2 + dataLength) {
          debugPrint('余下报文长度不够，重读');
          break;
        }

        const paramsStart = 4;
        final paramsEnd = 4 + (dataLength - 3);
        final paramsBytes = byteBuffer.sublist(paramsStart, paramsEnd);
        byteBuffer = byteBuffer.sublist(paramsEnd + 1);

        if (dataLength != 4 || paramsBytes.length != 1) {
          final data = DataConvert.bytesToHex(paramsBytes);
          final epc = data.substring(6, data.length - 14);
          // 发送更新通知
          _epcManager.addEpc(epc);
        }
      } catch (e) {
        byteBuffer.clear();
      }
    }
  }

  _decodeBacker(
    List<int> data,
  ) {
    for (int i = 0; i < data.length; ++i) {
      int temp = data[i];
      if (!_headed) {
        if (_hindex < _head.length && temp == _head[_hindex]) {
          ++_hindex;
          if (_hindex == _head.length) {
            _headed = true;
            _index = 0;
            _frameLen = 0;
            _hindex = 0;
            _recBuf[_index++] = temp;
            continue;
          }
        } else {
          _hindex = 0;
        }
      } else {
        _recBuf[_index++] = temp;
        if (_index == 14) {
          // 帧长度解析，严格对齐Java逻辑
          _frameLen = _recBuf[_index - 1] & 0xFF;
          _frameLen <<= 8;
          _frameLen &= 0xFF00;
          _frameLen |= _recBuf[_index - 2] & 0xFF;
          _frameLen += 20; // 根据实际协议调整帧长度
          continue;
        }
        if (_frameLen == _index && temp == 0xE9) {
          // 帧结束，调用_getData
          _headed = false;
          if (_index < 1000) {
            debugPrint("RX 读取到数据 $_index bytes [");
            debugPrint(DataConvert.getHexString(_recBuf, 0, _index));
          } else {
            int mlen = _index;
            while (mlen > 10) {
              if (mlen > 1000) {
                mlen -= 1000;
              } else {
                mlen -= mlen;
              }
            }
          }
          _getData(_index);
        }
      }
      if (_index > 5000) {
        _index = 5000;
      }
    }
  }

  void _getData(int length) {
    int checkSum = 0;
    int index = 18;
    String infos = "";

    // 计算校验和
    int j;
    for (j = 0; j < length - 2; ++j) {
      checkSum += _recBuf[j];
    }

    // 验证校验和和帧头
    if (_recBuf[j] == (checkSum & 0xFF) && _recBuf[11] == 0x97) {
      // 解析数据长度
      int dlen = (_recBuf[13] & 0xFF) << 8;
      dlen &= 0xFF00;
      dlen |= _recBuf[12] & 0xFF;

      // 设备信息解析 (0xB0, 0x01)
      if (_recBuf[16] == 0xB0 && _recBuf[17] == 1) {
        // 设备名称 (12字节)
        List<int> deviceName = List.generate(12, (_) => _recBuf[index++]);
        // MAC地址 (6字节)
        List<int> macAdd = List.generate(6, (_) => _recBuf[index++]);
        // 硬件版本 (2字节)
        List<int> hwVersion = List.generate(2, (_) => _recBuf[index++]);
        // 硬件时间 (3字节)
        List<int> hwTime = List.generate(3, (_) => _recBuf[index++]);
        // 软件版本 (4字节)
        List<int> swVersion = List.generate(4, (_) => _recBuf[index++]);
        // 软件时间 (3字节)
        List<int> swTime = List.generate(3, (_) => _recBuf[index++]);
        // 电池信息 (4字节)
        List<int> battery = List.generate(4, (_) => _recBuf[index++]);
        // 硬件模型 (4字节)
        List<int> hwModelByte = List.generate(4, (_) => _recBuf[index++]);
        // 电池容量 (2字节，小端序)
        int batCapMaH =
            ((_recBuf[index + 1] & 0xFF) << 8) | (_recBuf[index] & 0xFF);
        index += 2;
        // 厂商编码 (24字节)
        List<int> companyCode = List.generate(24, (_) => _recBuf[index++]);
        // 厂商名称 (变长)
        int nameLen = _recBuf[index++] & 0xFF;
        List<int> companyName = List.generate(nameLen, (_) => _recBuf[index++]);
        RfidDeviceInfo deviceInfo = RfidDeviceInfo();
        deviceInfo.fromRawData(
          deviceName: deviceName,
          macAdd: macAdd,
          hwVersion: hwVersion,
          hwTime: hwTime,
          swVersion: swVersion,
          swTime: swTime,
          battery: battery,
          hwModelByte: hwModelByte,
          batCapMaH: batCapMaH,
          companyCode: companyCode,
          companyName: companyName,
        );
        _sendResult(RfidResultType.deviceInfo, data: deviceInfo);
      }

      // 写入成功响应 (数据长度=0, 功能码=0x01 获取背夹信息, 子功能码=0x00)
      if (_recBuf[12] == 0 && _recBuf[16] == 1 && _recBuf[17] == 0) {
        infos += "写入成功";
        _sendResult(RfidResultType.unknown, message: infos);
      }

      // 电源状态读取 (0xB0, 0x03)
      if (_recBuf[16] == 0xB0 && _recBuf[17] == 3) {
        var voltage = _recBuf[18] & 0xFF; // 电压
        int quantity = _recBuf[19] & 0xFF; // 电量
        var data = {'voltage': voltage, 'quantity': quantity};
        _sendResult(RfidResultType.batteryInfo, data: data);
      }

      // 电源设置成功 (0xB0, 0x04)
      if (_recBuf[16] == 0xB0 && _recBuf[17] == 4) {
        infos += "电源设置成功";
        _sendResult(RfidResultType.batteryWrite, message: infos);
      }

      // 通信参数读取 (0xB0, 0x05)
      List<int> tagError;
      if (_recBuf[16] == 0xB0 && _recBuf[17] == 5) {
        if (dlen == 8) {
          tagError = List.filled(8, 0);
          for (int i = 0; i < tagError.length; i++) {
            tagError[i] = _recBuf[18 + i];
          }
          _sendResult(RfidResultType.uhfRfid, data: tagError);
        } else {
          infos += "通信参数读取失败${DataConvert.bcdStr(_recBuf[19])}";
          _sendResult(RfidResultType.uhfRfid, message: infos, isSuccess: false);
        }
      }

      // 通信参数设置 (0xB0, 0x06)
      if (_recBuf[16] == 0xB0 && _recBuf[17] == 6) {
        infos += "通信参数 ";
        if (dlen == 0) {
          infos += "设置成功";
        } else {
          infos += DataConvert.bcdStr(_recBuf[19]);
        }
        _sendResult(RfidResultType.uhfRfidWrite, message: infos);
      }

      // UHF设置响应 (0x20, 0x01)
      if (_recBuf[16] == 0x20 && _recBuf[17] == 1) {
        tagError = List.filled(dlen, 0);
        for (int i = 0; i < dlen; i++) {
          tagError[i] = _recBuf[18 + i];
        }

        if (dlen < 8) {
          _sendResult(RfidResultType.txPower,
              message: DataConvert.getTagErrorCode(tagError), isSuccess: false);
        } else {
          var arg2 = dlen;
          if (arg2 != -1) {
            int regin = tagError[1] & 0xFF;
            int dbm = tagError[0] & 0xFF;
            _uhfRFset = tagError;
            // 工作区域和发射功率
            var obj = {'regin': regin, 'dbm': dbm};
            _sendResult(RfidResultType.txPower, data: obj);
          }
        }
      }

      // UHF功率设置响应 (0x20, 0x02)
      tagError = List.filled(4, 0);
      if (_recBuf[16] == 0x20 && _recBuf[17] == 2) {
        if (dlen == 0) {
          _sendResult(RfidResultType.txPowerWrite, message: "UHF设置功率成功！");
        } else {
          List<int> back = List.filled(dlen, 0);
          for (int i = 0; i < dlen; i++) {
            back[i] = _recBuf[18 + i];
          }
          _sendResult(RfidResultType.txPowerWrite,
              message: DataConvert.getTagErrorCode(back), isSuccess: false);
        }
      }

      // 写标签响应 (0x20, 0x09)
      if (_recBuf[16] == 0x20 && _recBuf[17] == 9) {
        if (dlen == 4) {
          tagError[0] = _recBuf[18];
          tagError[1] = _recBuf[19];
          tagError[2] = _recBuf[20];
          tagError[3] = _recBuf[21];
          _sendResult(RfidResultType.epcWrite,
              message: DataConvert.getTagErrorCode(tagError), isSuccess: false);
        } else {
          _sendResult(RfidResultType.epcWrite, message: "写入成功");
        }
      }

      // EPC锁定标签 (0x20, 0x0A)
      if (_recBuf[16] == 0x20 && _recBuf[17] == 10) {
        if (dlen == 4) {
          tagError[0] = _recBuf[18];
          tagError[1] = _recBuf[19];
          tagError[2] = _recBuf[20];
          tagError[3] = _recBuf[21];
          _sendResult(RfidResultType.epcLock,
              message: "EPC锁定标签失败 ${DataConvert.getTagErrorCode(tagError)}",
              isSuccess: false);
        } else {
          _sendResult(RfidResultType.epcLock, message: "EPC锁定标签成功");
        }
      }

      // GB写标签响应 (0x20, 0x10)
      if (_recBuf[16] == 0x20 && _recBuf[17] == 16) {
        if (dlen == 4) {
          tagError[0] = _recBuf[18];
          tagError[1] = _recBuf[19];
          tagError[2] = _recBuf[20];
          tagError[3] = _recBuf[21];
          _sendResult(RfidResultType.gbWrite,
              message: DataConvert.getTagErrorCode(tagError), isSuccess: false);
        } else {
          _sendResult(RfidResultType.gbWrite, message: "写入成功");
        }
      }

      // GB锁定标签 (0x20, 0x11)
      if (_recBuf[16] == 0x20 && _recBuf[17] == 17) {
        if (dlen == 4) {
          tagError[0] = _recBuf[18];
          tagError[1] = _recBuf[19];
          tagError[2] = _recBuf[20];
          tagError[3] = _recBuf[21];
          _sendResult(RfidResultType.gbLock,
              message: "GB锁定标签失败 ${DataConvert.getTagErrorCode(tagError)}",
              isSuccess: false);
        } else {
          _sendResult(RfidResultType.gbLock, message: "GB锁定标签成功");
        }
      }

      // EPC灭活标签 (0x20, 0x0B)
      if (_recBuf[16] == 0x20 && _recBuf[17] == 11) {
        if (dlen == 4) {
          tagError[0] = _recBuf[18];
          tagError[1] = _recBuf[19];
          tagError[2] = _recBuf[20];
          tagError[3] = _recBuf[21];
          _sendResult(RfidResultType.epcInactivate,
              message: "EPC灭活标签失败 ${DataConvert.getTagErrorCode(tagError)}",
              isSuccess: false);
        } else {
          _sendResult(RfidResultType.epcInactivate, message: "EPC灭活标签成功");
        }
      }

      // GB灭活标签 (0x20, 0x12)
      if (_recBuf[16] == 0x20 && _recBuf[17] == 18) {
        if (dlen == 4) {
          tagError[0] = _recBuf[18];
          tagError[1] = _recBuf[19];
          tagError[2] = _recBuf[20];
          tagError[3] = _recBuf[21];
          _sendResult(RfidResultType.gbInactivate,
              message: "GB灭活标签失败 ${DataConvert.getTagErrorCode(tagError)}",
              isSuccess: false);
        } else {
          _sendResult(RfidResultType.gbInactivate, message: "GB灭活标签成功");
        }
      }

      // 读标签响应 - EPC (0x20, 0x08),读取标签返回数据
      List<int> tagData;
      int epcLen;
      if (_recBuf[16] == 0x20 && _recBuf[17] == 8) {
        if (dlen == 4) {
          tagError[0] = _recBuf[18];
          tagError[1] = _recBuf[19];
          tagError[2] = _recBuf[20];
          tagError[3] = _recBuf[21];
          _sendResult(RfidResultType.epcRead, data: null);
        } else {
          epcLen = _recBuf[18] & 0xFF;
          epcLen *= 2;
          tagData = List.filled(epcLen, 0);
          for (int i = 0; i < epcLen; ++i) {
            tagData[i] = _recBuf[19 + i];
          }
          var res = DataConvert.getHexString(tagData, 0, epcLen);
          _sendResult(RfidResultType.epcRead, data: res);
        }
      }

      // 读标签响应 - GB (0x20, 0x0F)
      if (_recBuf[16] == 0x20 && _recBuf[17] == 15) {
        if (dlen == 4) {
          tagError[0] = _recBuf[18];
          tagError[1] = _recBuf[19];
          tagError[2] = _recBuf[20];
          tagError[3] = _recBuf[21];
          _sendResult(RfidResultType.gbRead,
              message: DataConvert.getTagErrorCode(tagError), isSuccess: false);
        } else {
          epcLen = _recBuf[18] & 0xFF;
          epcLen *= 2;
          tagData = List.filled(epcLen, 0);
          for (int i = 0; i < epcLen; i++) {
            tagData[i] = _recBuf[19 + i];
          }
          _sendResult(RfidResultType.gbRead,
              data: DataConvert.getHexString(tagData, 0, epcLen));
        }
      }

      // 寻标签响应 (0x20, 0x05 或 0x20, 0xAA)
      String tid = '';
      String epc = '';
      if ((_recBuf[16] == 0x20 && _recBuf[17] == 5) ||
          (_recBuf[16] == 0x20 && _recBuf[17] == 0xAA)) {
        if (_recBuf[18] == 0) {
          epcLen = _recBuf[19] & 0xFF;
          epcLen *= 2;
          epc = DataConvert.getHexString(_recBuf, 20, epcLen);
          epc = epc.replaceAll(" ", "");
          infos += "EPC: $epc";

          if (dlen > epcLen + 3) {
            index = 20 + epcLen;
            epcLen = _recBuf[index++] & 0xFF;
            epcLen *= 2;
            tid = DataConvert.getHexString(_recBuf, index, epcLen);
            tid = tid.replaceAll(" ", "");
            epc = "$epc\n$tid";
            infos += "TID: $tid";
          }

          _epcManager.addEpc(epc, tid: tid);
          _sendResult(RfidResultType.labelSearch,
              data: {'epc': epc, 'tid': tid});
        }
      }

      // GB寻标签响应 (0x20, 0x0C)
      if (_recBuf[16] == 0x20 && _recBuf[17] == 12) {
        if (_recBuf[18] == 0) {
          epcLen = _recBuf[20] & 0xFF;
          epcLen *= 2;
          epc = DataConvert.getHexString(_recBuf, 0, epcLen);
          epc = epc.replaceAll(" ", "");
          infos += "EPC: $epc";

          if (dlen > epcLen + 4) {
            index = 21 + epcLen;
            epcLen = _recBuf[index++] & 0xFF;
            epcLen *= 2;
            tid = DataConvert.getHexString(_recBuf, 0, epcLen);
            tid = tid.replaceAll(" ", "");
            epc = "$epc\n$tid";
            infos += "TID: $tid";
          }

          _epcManager.addEpc(epc, tid: tid);
          _sendResult(RfidResultType.labelSearch,
              data: {'epc': epc, 'tid': tid});
        } else {
          _sendResult(RfidResultType.labelSearch, data: null);
        }
      }

      // 电池电压读取 (0x01, 0x02)
      if (_recBuf[16] == 1 && _recBuf[17] == 2) {
        String voltageStr =
            "${DataConvert.bcdStr(_recBuf[18])}.${DataConvert.bcdStr(_recBuf[19])}V";
        infos = "$voltageStr   ";
        infos += "${DataConvert.bcdStr(_recBuf[20])}%";
        _sendResult(RfidResultType.batteryInfo, data: infos);
      }

      // 设备功能响应 (0xB0, 0x07)
      if (_recBuf[16] == 0xB0 && _recBuf[17] == 7) {
        _parseDeviceResponse(dlen, infos);
      }
    }
  }

  // 添加缺少的属性
  int _mDeviceCMD = 0;

  // 设备响应解析方法
  void _parseDeviceResponse(
    int dlen,
    String infos,
  ) {
    String codeStr;
    List<int> code;

    // 二维码/扫码数据 (10 或 34)
    if (_recBuf[18] == 10 || _recBuf[18] == 34) {
      if (_mDeviceCMD != _recBuf[19] && _recBuf[19] != 26) {
        _sendResult(RfidResultType.qrCode,
            message: DataConvert.bcdStr(_recBuf[19]), isSuccess: false);
        return;
      }

      // 解析数据长度 (小端序)
      int dataLen = (_recBuf[21] & 0xFF) << 8;
      dataLen &= 0xFF00;
      dataLen |= _recBuf[20] & 0xFF;

      // 提取数据
      code = List.filled(dataLen, 0);
      for (int i = 0; i < dataLen; i++) {
        code[i] = _recBuf[22 + i];
      }

      // 转换为UTF-8字符串
      try {
        codeStr = String.fromCharCodes(code);
      } catch (e) {
        debugPrint("UTF-8解码错误: $e");
        codeStr = "解码失败";
      }
      _sendResult(RfidResultType.qrCode, data: codeStr);
    }

    // 高频RFID卡数据 (23)
    if (_recBuf[18] == 23) {
      if (_mDeviceCMD != _recBuf[19] && _recBuf[19] != 26) {
        _sendResult(RfidResultType.uhfRfid,
            message: DataConvert.bcdStr(_recBuf[19]), isSuccess: false);
        return;
      }

      // 解析数据长度 (小端序)
      int dataLen = (_recBuf[21] & 0xFF) << 8;
      dataLen &= 0xFF00;
      dataLen |= _recBuf[20] & 0xFF;

      // 提取数据
      code = List.filled(dataLen, 0);
      for (int i = 0; i < dataLen; i++) {
        code[i] = _recBuf[22 + i];
      }

      if (_mDeviceCMD == 92) {
        // NFC数据解码
        codeStr = _decodeNFCData(code);
        _sendResult(RfidResultType.uhfRfid, data: codeStr);
      } else {
        // 转换为十六进制字符串
        codeStr = DataConvert.getHexString(code, 0, code.length);
        _sendResult(RfidResultType.uhfRfid, data: codeStr);
      }
    }

    // 安全模块数据 (32)
    if (_recBuf[18] == 32) {
      if (_mDeviceCMD != _recBuf[19]) {
        _sendResult(RfidResultType.securityData,
            message: DataConvert.bcdStr(_recBuf[19]), isSuccess: false);
        return;
      }

      // 解析数据长度 (小端序)
      int dataLen = (_recBuf[21] & 0xFF) << 8;
      dataLen &= 0xFF00;
      dataLen |= _recBuf[20] & 0xFF;

      // 提取数据
      code = List.filled(dataLen, 0);
      for (int i = 0; i < dataLen; i++) {
        code[i] = _recBuf[22 + i];
      }

      // 转换为十六进制字符串
      codeStr = DataConvert.getHexString(code, 0, code.length);
      _sendResult(RfidResultType.securityData, data: codeStr);
    }

    // 485抄表数据 (25, 24, 9)
    if (_recBuf[18] == 25 || _recBuf[18] == 24 || _recBuf[18] == 9) {
      if (_mDeviceCMD != _recBuf[19]) {
        _sendResult(RfidResultType.irRayData,
            message: DataConvert.bcdStr(_recBuf[19]), isSuccess: false);
        return;
      }

      // 解析数据长度 (小端序)
      int dataLen = (_recBuf[21] & 0xFF) << 8;
      dataLen &= 0xFF00;
      dataLen |= _recBuf[20] & 0xFF;

      // 提取数据
      code = List.filled(dataLen, 0);
      for (int i = 0; i < dataLen; i++) {
        code[i] = _recBuf[22 + i];
      }

      // 转换为十六进制字符串
      codeStr = DataConvert.getHexString(code, 0, code.length);
      var data = {'code': _recBuf[18] & 0xFF, 'codeStr': codeStr};

      _sendResult(RfidResultType.irRayData, data: data);
    }
  }

  // NFC数据解码方法（如果需要特殊解码逻辑）
  String _decodeNFCData(List<int> data) {
    // 这里可以根据具体需求实现NFC数据的特殊解码逻辑
    // 目前使用简单的UTF-8解码
    try {
      return String.fromCharCodes(data);
    } catch (e) {
      debugPrint("NFC数据解码错误: $e");
      // 如果UTF-8解码失败，返回十六进制字符串
      return DataConvert.getHexString(data, 0, data.length);
    }
  }

  // 取消选择GB标签
  Future<void> unSelectGBTag() async {
    _funcByte0 = 0x20;
    _funcByte1 = 14;
    await sendRFIDCmd([]);
  }

  // 取消选择EPC标签
  Future<void> unSelectEPCTag() async {
    _funcByte0 = 0x20;
    _funcByte1 = 0x07;
    await sendRFIDCmd([]);
  }

  // 读取端口
  Future<void> readPort(List<int> data) async {
    _funcByte0 = -80; // -80的十六进制表示
    _funcByte1 = 5;
    await sendRFIDCmd(data, len: data.length);
  }

  // 设置端口
  Future<void> setPort(List<int> data) async {
    _funcByte0 = -80; // -80的十六进制表示
    _funcByte1 = 6;
    await sendRFIDCmd(data, len: data.length);
  }

  // 选择的EPC标签
  Future<void> selectEPCTag(String epc) async {
    int index = 0;
    bool epcArea = true;

    // 处理EPC字符串
    if (epc.contains('\n')) {
      List<String> div = epc.split('\n');
      if (div.length == 1) {
        epc = div[0];
        epcArea = true;
      } else {
        epc = div[1];
        epcArea = false;
      }
    }

    // 转换EPC字符串为字节数组
    List<int> tag = DataConvert.getStringHex(epc);
    List<int> data = List.filled(tag.length + 4, 0);

    // 设置功能字节
    _funcByte0 = 0x20;
    _funcByte1 = 0x06;

    // 设置区域标志
    data[index++] = epcArea ? 0 : 1;

    // 设置偏移量
    data[index++] = 0;
    data[index++] = 0;

    // 设置长度
    if (tag.length * 8 < 255) {
      data[index++] = (tag.length * 8) & 0xFF;
    } else {
      data[index++] = -1 & 0xFF;
    }

    // 复制标签数据
    for (int i = 0; i < tag.length; ++i) {
      data[index++] = tag[i];
    }

    // 发送RFID命令
    await sendRFIDCmd(data, len: data.length);
  }

  // 读取设备信息
  Future<void> readDeviceInfo() async {
    _funcByte0 = 0xB0;
    _funcByte1 = 0x01;
    await sendRFIDCmd([]);
  }

  // 读取电池信息
  Future<void> readBat() async {
    _funcByte0 = 0x01;
    _funcByte1 = 0x02;
    await sendRFIDCmd([]);
  }

  // 模块类型:模式切换（条码/UHF/高频RFID)
  Future<void> setPower(int on, {int device = 5}) async {
    _funcByte0 = -80;
    _funcByte1 = 4;

    List<int> data = [device, on];
    await sendRFIDCmd(data, len: data.length);
  }

  // 读取设备电源状态
  Future<void> readDevicePower(int index) async {
    List<int> deviceCode = [23, 10, 24, 25, 32, 9, 1];
    if (index < deviceCode.length) {
      _funcByte0 = -80;
      _funcByte1 = 0x03;
      List<int> data = [deviceCode[index]];
      await sendRFIDCmd(data, len: data.length);
    }
  }

  // 读取安全模块
  Future<void> readSecurity() async {
    _funcByte0 = -80;
    _funcByte1 = 0x07;
    List<int> data = [32, 2, 9, 0, 0xE9, 0, 4, 1, 1, 1, 8, 0xF8, 0xE6];
    await sendRFIDCmd(data);
  }

  // 读取二维码
  Future<void> readQRCode() async {
    List<int> data = [0x22, 01, 00, 00];
    _funcByte0 = -80; // -80的十六进制表示
    _funcByte1 = 7;
    _mDeviceCMD = 1;
    await sendRFIDCmd(data, len: data.length);
  }

  // 高频RFID寻卡
  Future<void> readRFIDCard() async {
    List<int> data = [23, 6, 0, 0];
    _funcByte0 = -80; // -80的十六进制表示
    _funcByte1 = 7;
    _mDeviceCMD = 6;
    await sendRFIDCmd(data, len: data.length);
  }

  // 读取设置
  Future<void> readTxPower() async {
    _funcByte0 = 0x20;
    _funcByte1 = 1;
    await sendRFIDCmd([]);
  }

  writeTxPower(int dbm, int regin) {
    if (_uhfRFset.length < 5) {
      return;
    }
    _funcByte0 = 0x20;
    _funcByte1 = 2;
    _uhfRFset[0] = dbm;
    _uhfRFset[1] = regin;
    sendRFIDCmd(_uhfRFset, len: _uhfRFset.length);

    // 清空数据
  }

  // UHF EPC盘存
  Future<void> uhfSearchTag(bool enable) async {
    _funcByte0 = 0x20; //32
    _funcByte1 = enable ? 0x0C : 0x05;
    List<int> cmd = [0, 0, 1, 0, 0, 0, 0, 0];
    await sendRFIDCmd(cmd, len: cmd.length);
  }

  // UHF EPC+TID盘存
  Future<void> uhfSearchTagTID(bool enable) async {
    _funcByte0 = 0x20; //32
    _funcByte1 = enable ? 0x0C : 0x05;
    List<int> cmd = [1, 0, 1, 0, 0, 0, 0, 0];
    await sendRFIDCmd(cmd, len: cmd.length);
  }

  // 读取标签数据
  Future<void> uhfReadTag(
      int area, int offset, int length, List<int> code) async {
    _funcByte0 = 0x20; //32
    _funcByte1 = 0x08; // 8
    int index = 0;
    List<int> data = List.filled(9, 0);
    data[index++] = 0;
    data[index++] = area & 0xFF;
    data[index++] = (offset & 0xFF);
    data[index++] = (offset >> 8 & 0xFF);
    data[index++] = length & 0XFF;

    int i;
    for (i = 0; i < 4; ++i) {
      data[index++] = code[i];
    }
    await sendRFIDCmd(data, len: data.length);
  }

  onUHFWritEpc(String epcStr) async {
    String data = epcStr.replaceAll(" ", '');
    if (data.length % 2 == 1) {
      data = "${data}0";
    }
    if (data.length % 4 != 0) {
      data = "${data}00";
    }
    List<int> dataBytes = DataConvert.getStringHex(data);

    await uhfWriteTag(
      EPCType.epc.index, // 区域
      0, // 偏移量
      DataConvert.getStringHex('00000000'),
      dataBytes, // 写入数据
    );
  }

  // 写入标签数据
  Future<void> uhfWriteTag(
      int area, int offset, List<int> code, List<int> dat) async {
    _funcByte0 = 0x20; //32
    _funcByte1 = 0x09; // 9
    int index = 0;
    List<int> data = List.filled(9 + dat.length, 0);
    data[index++] = 0;
    data[index++] = area & 0xFF;
    data[index++] = (offset & 0xFF);
    data[index++] = (offset >> 8 & 0xFF);

    int i;
    for (i = 0; i < 4; ++i) {
      data[index++] = code[i];
    }

    data[index++] = (dat.length ~/ 2);

    for (i = 0; i < dat.length; ++i) {
      data[index++] = dat[i];
    }
    await sendRFIDCmd(data, len: data.length);
  }

  // 锁定标签
  Future<void> uhfLockTag(bool isGB, int area, int mode, List<int> code) async {
    if (bleManager.isGW) {
      List<int> cmd = [32, 6, area, mode];
      cmd.addAll(code);
      await sendRFIDCmd(cmd);
    }
  }

  // 销毁标签
  Future<void> uhfKillTag(bool isGB, List<int> code) async {
    if (bleManager.isGW) {
      List<int> cmd = [32, 7];
      cmd.addAll(code);
      await sendRFIDCmd(cmd);
    }
  }

  // 3. 统一消息分发方法
  void _sendResult<T>(RfidResultType type,
      {T? data, String? message, bool isSuccess = true}) {
    _resultController.add(RfidResult<T>(
        type: type, data: data, message: message, isSuccess: isSuccess));
  }

  void clearTag() {
    _epcManager.clearEpcData();
  }
}
